//
//  MeController.swift
//  LiteAccount
//
//  Created by 刘伟 on 2017/5/4.
//  Copyright © 2017年 刘伟. All rights reserved.
//

import UIKit

class MeController: UIViewController, BaseViewProtocal {
    
    var userInfo: UserModel? {
        didSet {
            if userInfo != nil {
                tableView.reloadData()
            }
        }
    }
    
    var isLoaded = false

    override func viewDidLoad() {
        super.viewDidLoad()
        prepareUI()
        layoutUI()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        if Defaults[.token] == nil {
            tableView.reloadData()
            self.navigationItem.rightBarButtonItem?.customView?.isHidden = true
            return
        } else {
            self.navigationItem.rightBarButtonItem?.customView?.isHidden = false
        }
        if !isLoaded {
            loadData()
        }
    }
    
    var data = [
//        ["message","我的消息"],
//        ["favorites","我的收藏"],
//        ["setting","我的设置"],
        ["me_gesture", "设置手势解锁"],
        ["me_about", "关于"]
    ]
    
    fileprivate func prepareUI() {
        self.edgesForExtendedLayout = .init(rawValue: 0)
        self.view.backgroundColor = UIColor.la_bg
        initMJHearder(target: tableView, selector: #selector(loadData))
        self.navigationItem.rightBarButtonItem = UIBarButtonItem.barButton("注销", titleColor: .white, target: self, action: #selector(logout))
        tableView.register(AvatarCell.self, forCellReuseIdentifier: "avatarCell")
        tableView.register(UserInfoCell.self, forCellReuseIdentifier: "userInfoCell")
        self.view.addSubview(tableView)
    }
    
    fileprivate func layoutUI() {
        tableView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
    }
    
    func loadData() {
        var params = [String: Any]()
        params["token"] = Defaults[.token]
        APIClient.shared.fetchUserInfo(params: params) { (response) in
            switch response {
            case let .success(data as UserModel, _):
                self.userInfo = data
            default: break
            }
            self.tableView.mj_header.endRefreshing()
        }
    }
    
    // MARK: 登出
    func logout() {
        let confirm = confirmDialog(title: "温馨提示", message: "亲，确定要注销登录吗？") {
            // 确认登出后，先跳转再执行退出请求
            jumpHomeTab(target: self)
            var params = [String: Any]()
            params["token"] = Defaults[.token]
            resetDefaults()
            APIClient.shared.requestLogout(params: params) { (response) in
                self.isLoaded = false
            }
        }
        self.present(confirm, animated: true, completion: nil)
    }
    
    
    fileprivate lazy var tableView: UITableView = { [unowned self] in
        let object = UITableView(frame: .zero, style: .grouped)
        object.backgroundColor = UIColor.la_bg
        object.dataSource = self
        object.delegate = self
        object.emptyDataSetSource = self
        object.emptyDataSetDelegate = self
        object.separatorStyle = .singleLine
        object.estimatedRowHeight = 100
        object.rowHeight = UITableViewAutomaticDimension
        object.tableFooterView = UIView()
        return object
    }()

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

extension MeController: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.001
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return (Defaults[.token] == nil) ? 0 : 1
        } else {
            return (Defaults[.token] == nil) ? 0 : self.data.count
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 10
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            return 100
        } else {
            return 40
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "avatarCell") as! AvatarCell
            cell.data = self.userInfo
            cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator
            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "userInfoCell") as! UserInfoCell
            cell.data = self.data[indexPath.row]
            cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 0 {
            let nextView = EditMeController()
            nextView.hidesBottomBarWhenPushed = true
            if let nickname = self.userInfo?.nickname {
                nextView.nickname = nickname
            }
            self.navigationController?.pushViewController(nextView, animated: true)
        }
        
        if indexPath.section == 1 && data[indexPath.row][1] == "设置手势解锁" {
            // 手势解锁
            let nextVC = ResetGestureController()
            nextVC.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(nextVC, animated: true)
        }
        
        if indexPath.section == 1 && data[indexPath.row][1] == "关于" {
            // 关于
            let nextView = AboutController()
            nextView.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(nextView, animated: true)
        }
        
    }
}

extension MeController: DZNEmptyDataSetSource, DZNEmptyDataSetDelegate {
    
    func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
        let image = resizeImage(image: UIImage(named: "app_icon_light_blue.png")!, toSize: CGSize(width: 150, height: 150))
        return image
    }
    
    func buttonTitle(forEmptyDataSet scrollView: UIScrollView, for state: UIControlState) -> NSAttributedString? {
        let text = "你还没有登录，点击登录"
        let font = UIFont.la_Font(ofSize: 15)
        let attrStr = NSMutableAttributedString.init(string: text)
        attrStr.addAttributes([NSFontAttributeName : font], range: NSMakeRange(0, 11))
        attrStr.addAttributes([NSForegroundColorAttributeName : UIColor.black], range: NSMakeRange(0, 6))
        attrStr.addAttributes([NSForegroundColorAttributeName : UIColor.la_app], range: NSMakeRange(7, 4))
        return attrStr
    }
    
    func backgroundColor(forEmptyDataSet scrollView: UIScrollView) -> UIColor? {
        return UIColor.white
    }
    
    func emptyDataSet(_ scrollView: UIScrollView, didTap view: UIView) {
    }
    
    func emptyDataSet(_ scrollView: UIScrollView, didTap button: UIButton) {
        if(checkLogin(target: self.tabBarController)){
            jumpHomeTab(target: self)
            self.isLoaded = false
            return
        }
    }
}




